const isJSON = function (str) {
    if (typeof str === 'string') {
      try {
        let obj = JSON.parse(str)
        if (typeof obj === 'object', obj) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
    }
  }
  
  const textWidth = function (text, fontSize) {
    let canvas = document.createElement('canvas')
    canvas.width = 200
    canvas.height = 20
    let ctx = canvas.getContext('2d')
    let font = 'px "Segoe UI", "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif'
    if (!fontSize) {
      fontSize = 14
    }
    font = fontSize + font
    ctx.font = font
    ctx.fillText(text, 0, 20)
    let metrics = ctx.measureText(text)
    return metrics.width
  }
  
  const convertTreePaths = function (tree, parentPath = '') {
    console.log('tree', tree)
    return _.flatMapDeep(tree, node => {
      const currentPath = parentPath ? `${parentPath}/${node.supMenuRefno}` : node.supMenuRefno
      node.fullPath = currentPath
      if (node.children) {
        return convertTreePaths(node.children, currentPath)
      }
    })
  }
  
  const buildMenuTree = function (menuData, menuRootId) {
    menuData=menuData.filter(item=>item.checked==='1')
    const items = []
    menuData.forEach(item => items[item.menuRefno] = { ...item, children: [] })
    const tree = []
    for (const item of Object.values(items)) {
      if (item.supMenuRefno === menuRootId) {
        tree.push(item)
      } else {
        const parent = items[item.supMenuRefno]
        parent && parent.children && parent.children.push(item)
      }
    }
    return tree
  }
  
  export { isJSON, textWidth, convertTreePaths, buildMenuTree }